﻿// This software is the confidential and proprietary information of NetBay.
// Such confidential information should not be disclosed.
// NetBay copyright(c) 2012

#region

using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Configuration;
using System.IO;
using System.Security;
using System.Web;
using NetBay.Core.BusinessEntities;
using NetBay.Core.Encryption;
using NetBay.Core.Encryption.Licensing;
using Rio.Applications.Web.Code;
using Rio.Applications.Web.RioWCFServices;
using Rio.Framework.RioManager;

#endregion

namespace Rio.Applications.Web
{
    public class Global : System.Web.HttpApplication
    {

        #region Instance Methods

        /// <summary>
        /// Handles the Error event of the Application control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected void Application_Error(object sender, EventArgs e)
        {
            Exception exc = Server.GetLastError();
            NetBay.Core.Log.LogManager.Instance().LogError(exc.ToString());
        }

        /// <summary>
        /// Here is the absolute first code of server RIO application is executed
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Application_Start(object sender, EventArgs e)
        {
            try
            {


                // Retreive path for configuration application
                string l_sConfiguration = ConfigurationManager.AppSettings.Get("Rio.Applications.Web.Configuration");
                if (string.IsNullOrEmpty(l_sConfiguration))
                {
                    l_sConfiguration = string.Format("{0}\\Rio.Applications.Web.Config", Server.MapPath("."));
                }

                string l_sDirectoryDA = Path.GetDirectoryName(l_sConfiguration);
                string l_sFileNameDA = Path.GetFileName(l_sConfiguration);

                // Retreive alias for DataBase connection
                string l_sDataBaseConnectionDA =
                    ConfigurationManager.AppSettings.Get("Rio.Applications.Web.DataBaseConnection");

                // Retrieve the default culture
                string l_sDefaultCulture = ConfigurationManager.AppSettings.Get("Rio.Applications.Web.DefaultCulture");

                // Initialise the Manager
                if (
                    MainManager.Init(l_sDirectoryDA, l_sFileNameDA, l_sDataBaseConnectionDA, l_sDefaultCulture,
                                     SaveSilverlightDeploymentSettings()) == false)
                {
                    LoggerManager.GetBusinessLogger.LogError("() Unable to load a good configuration so exit process!!!");
                    HttpRuntime.UnloadAppDomain();
                    return;
                }

                LicenseManager.RegisterLicense();

                // Clean rioscan path
                CleanScanUser();

                //Clean file services cache 
                CleanFilesServerCache();

                // First Trace
                LoggerManager.GetBusinessLogger.LogInfo(string.Empty);

            }
            catch (Exception ex)
            {
                LoggerManager.GetBusinessLogger.LogErrorFormat("Application start exception: {0}", ex.ToString());
                HttpRuntime.UnloadAppDomain();
                return;
            }
        }

        /// <summary>
        /// Handles the AuthenticateRequest event of the Application control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected void Application_AuthenticateRequest(Object sender, EventArgs e)
        {
            if (!LicenseManager.IsValidLicense && !HttpContext.Current.Request.CurrentExecutionFilePath.EndsWith("InvalidLicense.aspx"))
            {
                HttpContext.Current.Response.Redirect("~/InvalidLicense.aspx");
            }
        }

        /// <summary>
        /// Cleans the files server cache.
        /// </summary>
        private void CleanFilesServerCache()
        {
            try
            {
                using (WCFServiceClient L_oWCFServiceClient = new WCFServiceClient("BasicHttpBinding_IWCFService"))
                {
                    var p_oMessageRequest = new MessageRequest(AesEncryption.Encrypt(RioApplicationSettings.LicenseKey));
                    p_oMessageRequest.EncryptLicense(RioApplicationSettings.LicenseKeyDuration);
                    CleanCacheDirectoryRequest request = new CleanCacheDirectoryRequest(p_oMessageRequest);
                    L_oWCFServiceClient.CleanCacheDirectoryAsync(request);
                }
            }
            catch (Exception)
            {
            }
        }

        /// <summary>
        /// Cleans the scan.
        /// </summary>
        private void CleanScanUser()
        {
            try
            {
                string rioscanpath = string.Format("{0}{1}", AppDomain.CurrentDomain.BaseDirectory, @"\Rioscan");
                if (Directory.Exists(rioscanpath))
                {
                    string[] files = Directory.GetFiles(rioscanpath);
                    foreach (var item in files)
                    {
                        try
                        {
                            File.Delete(item);
                        }
                        catch
                        {
                        }
                    }
                }
            }
            catch
            {
            }
        }

        /// <summary>
        /// Saves the silverlight deployment settings.
        /// </summary>
        /// <returns></returns>
        private Dictionary<string, string> SaveSilverlightDeploymentSettings()
        {
            NameValueCollection appSettings = ConfigurationManager.AppSettings;
            Dictionary<string, string> l_oAppSettings = new Dictionary<string, string>();

            int SettingCount = appSettings.Count;
            for (int Idex = 0; Idex < SettingCount; Idex++)
            {
                l_oAppSettings.Add(appSettings.GetKey(Idex), appSettings[Idex]);
            }

            return l_oAppSettings;
        }


        #endregion
    }
}